Content with notebooks
Contents
Content with notebooks¶
You can also create content with Jupyter Notebooks. This means that you can include code blocks and their outputs in your book.
Markdown + notebooks¶
As it is markdown, you can embed images, HTML, etc into your posts!
You can also \(add_{math}\) and
or
But make sure you $Escape $your $dollar signs $you want to keep!
MyST markdown¶
MyST markdown works in Jupyter Notebooks as well. For more information about MyST markdown, check out the MyST guide in Jupyter Book, or see the MyST markdown documentation.
Code blocks and outputs¶
Jupyter Book will also embed your code blocks and output in your book. For example, here’s some sample Matplotlib code:
from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
<matplotlib.pyplot._IonContext at 0x2d136db9ff0>
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
Line2D([0], [0], color=cmap(.5), lw=4),
Line2D([0], [0], color=cmap(1.), lw=4)]
fig, ax = plt.subplots(figsize=(10, 5))
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);
import ipywidgets as widgets
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='d'
)
# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install numpy
Requirement already satisfied: numpy in c:\users\rimsha\turingenv\lib\site-packages (1.22.1)
WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available.
You should consider upgrading via the 'C:\Users\rimsha\turingenv\Scripts\python.exe -m pip install --upgrade pip' command.
There is a lot more that you can do with outputs (such as including interactive outputs) with your book. For more information about this, see the Jupyter Book documentation
import numpy as np
from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
!{sys.executable} -m pip install plotly
Requirement already satisfied: plotly in c:\users\rimsha\turingenv\lib\site-packages (5.5.0)
Requirement already satisfied: tenacity>=6.2.0 in c:\users\rimsha\turingenv\lib\site-packages (from plotly) (8.0.1)
Requirement already satisfied: six in c:\users\rimsha\turingenv\lib\site-packages (from plotly) (1.16.0)
WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available.
You should consider upgrading via the 'C:\Users\rimsha\turingenv\Scripts\python.exe -m pip install --upgrade pip' command.
from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
<matplotlib.pyplot._IonContext at 0x2d1490d9bd0>
import ipywidgets as widgets
widgets.ColorPicker(
concise=False,
description='Pick a color',
value='blue',
disabled=False
)
import ipywidgets as widgets
widgets.DatePicker(
description='Pick a Date',
disabled=False
)
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
from IPython.display import Image
Image("peacock.jpg")
from IPython.display import YouTubeVideo
SalidaVideo = widgets.Output()
with SalidaVideo:
display(YouTubeVideo('DsROfrRB-1k', width=500, height=500))
Salidas = widgets.HBox([SalidaVideo])
display(Salidas)
import ipywidgets as widgets
widgets.Combobox(
# value='John',
placeholder='Choose Someone',
options=['Peter', 'Rimy', 'Pinky', 'Ringo'],
description='Combobox:',
ensure_option=True,
disabled=False
)
import plotly.express as px
df = px.data.tips()
fig = px.parallel_categories(df, color="size", color_continuous_scale=px.colors.sequential.Inferno)
fig
import ipywidgets as widgets
container2 = widgets.HBox([origin, textbox])
widgets.VBox([container,
container2,
g])
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [16], in <module>
1 import ipywidgets as widgets
----> 2 container2 = widgets.HBox([origin, textbox])
3 widgets.VBox([container,
4 container2,
5 g])
NameError: name 'origin' is not defined
%%html
<img src = 'https://cloud.githubusercontent.com/assets/12302455/16637308/4e476280-43ac-11e6-9fd3-ada2c9506ee1.gif' >
df = pd.read_csv(
'https://raw.githubusercontent.com/yankev/testing/master/datasets/nycflights.csv')
df = df.drop(df.columns[[0]], axis=1
Input In [4]
df = df.drop(df.columns[[0]], axis=1
^
SyntaxError: '(' was never closed
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
df = px.data.iris()
all_dims = ['sepal_length', 'sepal_width',
'petal_length', 'petal_width']
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(
id="dropdown",
options=[{"label": x, "value": x}
for x in all_dims],
value=all_dims[:2],
multi=True
),
dcc.Graph(id="splom"),
])
@app.callback(
Output("splom", "figure"),
[Input("dropdown", "value")])
def update_bar_chart(dims):
fig = px.scatter_matrix(
df, dimensions=dims, color="species")
return fig
app.run_server(debug=True)
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Input In [5], in <module>
----> 1 import dash
2 import dash_core_components as dcc
3 import dash_html_components as html
ModuleNotFoundError: No module named 'dash'
import datetime
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from ipywidgets import widgets
# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install pandas
Collecting pandas
Using cached pandas-1.4.0-cp310-cp310-win_amd64.whl (10.6 MB)
Requirement already satisfied: python-dateutil>=2.8.1 in c:\users\rimsha\appdata\local\programs\python\python310\lib\site-packages (from pandas) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in c:\users\rimsha\appdata\local\programs\python\python310\lib\site-packages (from pandas) (2021.3)
Requirement already satisfied: numpy>=1.21.0 in c:\users\rimsha\appdata\local\programs\python\python310\lib\site-packages (from pandas) (1.22.1)
Requirement already satisfied: six>=1.5 in c:\users\rimsha\appdata\local\programs\python\python310\lib\site-packages (from python-dateutil>=2.8.1->pandas) (1.16.0)
Installing collected packages: pandas
Successfully installed pandas-1.4.0
WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available.
You should consider upgrading via the 'C:\Users\rimsha\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.
df = pd.read_csv(
'https://raw.githubusercontent.com/yankev/testing/master/datasets/nycflights.csv')
df = df.drop(df.columns[[0]], axis=1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [13], in <module>
----> 1 df = pd.read_csv(
2 'https://raw.githubusercontent.com/yankev/testing/master/datasets/nycflights.csv')
3 df = df.drop(df.columns[[0]], axis=1)
NameError: name 'pd' is not defined
df.sample(3)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [14], in <module>
----> 1 df.sample(3)
NameError: name 'df' is not defined
df = pd.read_csv(
'https://raw.githubusercontent.com/yankev/testing/master/datasets/nycflights.csv')
df = df.drop(df.columns[[0]], axis=1)
df.sample(3)
| year | month | day | dep_time | dep_delay | arr_time | arr_delay | carrier | tailnum | flight | origin | dest | air_time | distance | hour | minute | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 265957 | 2013 | 7 | 17 | 1507.0 | 2.0 | 1822.0 | -13.0 | AA | N365AA | 1769 | JFK | MIA | 149.0 | 1089 | 15.0 | 7.0 |
| 214839 | 2013 | 5 | 23 | NaN | NaN | NaN | NaN | US | NaN | 2134 | LGA | BOS | NaN | 184 | NaN | NaN |
| 27409 | 2013 | 10 | 1 | 1221.0 | -9.0 | 1350.0 | -15.0 | AA | N489AA | 329 | LGA | ORD | 117.0 | 733 | 12.0 | 21.0 |
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin",
marginal_x="box", trendline="ols", template="simple_white")
fig.show()
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Input In [22], in <module>
1 import plotly.express as px
2 df = px.data.iris()
----> 3 fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin",
4 marginal_x="box", trendline="ols", template="simple_white")
5 fig.show()
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\plotly\express\_chart_types.py:66, in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, orientation, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_options, trendline_color_override, trendline_scope, log_x, log_y, range_x, range_y, render_mode, title, template, width, height)
12 def scatter(
13 data_frame=None,
14 x=None,
(...)
60 height=None,
61 ):
62 """
63 In a scatter plot, each row of `data_frame` is represented by a symbol
64 mark in 2D space.
65 """
---> 66 return make_figure(args=locals(), constructor=go.Scatter)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\plotly\express\_core.py:2123, in make_figure(args, constructor, trace_patch, layout_patch)
2120 elif args["ecdfnorm"] == "percent":
2121 group[var] = 100.0 * group[var] / group_sum
-> 2123 patch, fit_results = make_trace_kwargs(
2124 args, trace_spec, group, mapping_labels.copy(), sizeref
2125 )
2126 trace.update(patch)
2127 if fit_results is not None:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\plotly\express\_core.py:358, in make_trace_kwargs(args, trace_spec, trace_data, mapping_labels, sizeref)
356 trace_patch["x"] = sorted_trace_data[args["x"]][non_missing]
357 trendline_function = trendline_functions[attr_value]
--> 358 y_out, hover_header, fit_results = trendline_function(
359 args["trendline_options"],
360 sorted_trace_data[args["x"]],
361 x,
362 y,
363 args["x"],
364 args["y"],
365 non_missing,
366 )
367 assert len(y_out) == len(
368 trace_patch["x"]
369 ), "missing-data-handling failure in trendline code"
370 trace_patch["y"] = y_out
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\plotly\express\trendline_functions\__init__.py:43, in ols(trendline_options, x_raw, x, y, x_label, y_label, non_missing)
37 if k not in valid_options:
38 raise ValueError(
39 "OLS trendline_options keys must be one of [%s] but got '%s'"
40 % (", ".join(valid_options), k)
41 )
---> 43 import statsmodels.api as sm
45 add_constant = trendline_options.get("add_constant", True)
46 log_x = trendline_options.get("log_x", False)
ModuleNotFoundError: No module named 'statsmodels'
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group")
fig.show()